<template>
  <!-- -->
  <a-table v-bind="$attrs" :dataSource="mDataSource" :pagination="simple ? false : mPagination" :columns="mColumns"
    :rowKey="rowKey" :size="sizeRef" @change="handleTableChange" @expand="onexpand">
    <template #[key]="data" v-for="(item, key) in $slots">
      <slot :name="key" v-bind="data || {}"></slot>
    </template>

    <template #title>
      <TableToolbar ref="tableToolbarRef" :cacheKey="cacheKey" :showSettings="showSettings" :regisiter="regisiter"
        :columns="columns">
        <template #tableToolbarLeft>
          <slot name="tableToolbarLeft"></slot>
        </template>

        <template #tableToolbarCenter>
          <slot name="tableToolbarCenter"></slot>
        </template>

        <template #tableToolbarRight>
          <slot name="tableToolbarRight"></slot>
        </template>
      </TableToolbar>
    </template>
  </a-table>
</template>

<script setup lang="ts">
import { PropType, onMounted, ref, watch, h, computed, defineEmits, inject, reactive } from 'vue';
import type { PaginationProps } from 'ant-design-vue';
import request from '/@/utils/request'
import { SorterResult } from 'ant-design-vue/es/table/interface';
import { TreeNode, TreeNodeProps } from '/@/utils/tree';
import TableAction from './TableAction.vue'
import TableToolbar from './TableToolbar.vue';
import { ActionItem, MTableColumnType, TableActionType } from './types';
import ViewMap from '/@/components/view'
import { useUserStore } from '/@/store/modules/user';
import dayjs from 'dayjs'

const userStore = useUserStore()
// 定义事件
const emits = defineEmits(['change', 'roleID', 'parentOrgID'])


const handleMoney: any = inject('handleMoney')
const oilPipeName: any = inject('oilPipeName')
const handleSend = (daya: any) => {
  // 调用爷爷传递函数，并把孙子组件中的值传递给爷爷组件
  handleMoney(daya)
}
const isSwitchOk: any = inject('isSwitchOk')
const switchOk = (daya: any) => {
  // 调用爷爷传递函数，并把孙子组件中的值传递给爷爷组件
  isSwitchOk(daya)
}
// 定义属性
const props = defineProps({
  api: { // 接口地址或接口函数--->新增属性
    type: [Function, String] as PropType<((param: any) => Promise<any>) | String>
  },
  query: {
    type:String
  },
  pagination: { // 当这里定义了和attrs一样的属性的时候，v-bind="$attrs"就会忽略该属性
    type: Object as PropType<PaginationProps>
  },
  defaultSorter: { // 排序的默认配置--->新增属性
    type: Object as PropType<SorterResult>
  },
  columns: { // 列定义，当这里定义了和attrs一样的属性的时候，v-bind="$attrs"就会忽略该属性
    type: Array as PropType<MTableColumnType[]>,
    default() {
      return []
    }
  },
  simple: { // 简单数据--树，id/parentId/name
    type: Object as PropType<TreeNodeProps>
  },
  rowKey: {
    type: [String],
    default: 'id'
  },
  title: {
    type: [String],
    default: ''
  },
  expandedKeys: {
    type: [String],
    default: 'id'
  },
  actions: { // 操作列
    type: Object as PropType<ActionItem[]>
  },
  dropdownActions: { // 下拉操作
    type: Object as PropType<ActionItem[]>
  },
  showSettings: { // 是否显示最右边设置区
    type: Boolean,
    default: true
  },
  size: { // 表格大小
    type: String
  },
  cacheKey: { // 缓存key
    type: String
  },
  // 是否立即执行
  immediate: {
    type: Boolean,
    default: true
  },
  params: { // 静态请求参数
    type: Object as PropType<any>
  },
  beforeFetch: { // 请求参数动态处理
    type: Function as PropType<(p: any) => any>
  }
})
const sizeRef = ref<String | undefined>(props.size)
const tableToolbarRef = ref()
watch(() => props.size, () => {
  sizeRef.value = props.size
})

// 定义排序对象
const mSorter = ref<SorterResult>({
  order: 'ascend',
  ...props.defaultSorter
})
/**
 * 将id/pid/name数据==>children数据
 * @param data 
 */
const toTreeData = (data: Array<any>) => {
  const res = new TreeNode(props.simple || {}).build(data, '0')
  return res
}
/**
 * 处理表格列定义数据
 * @param arr 
 */
const handleColumns = (arr: Array<MTableColumnType>) => {
  if (!props.defaultSorter) {
    // 如果默认的排序字段未配置，则使用第一个定义有sorter和defaultSortOrder的列
    const defaultSorterColumn: MTableColumnType | undefined = arr?.find(column => {
      return column.sorter && column.defaultSortOrder
    })
    if (defaultSorterColumn) {
      mSorter.value = {
        ...mSorter.value,
        field: defaultSorterColumn.key,
        order: defaultSorterColumn.defaultSortOrder
      }
    }
  }
  arr?.forEach(column => {
    // 处理默认排序
    if (column.key == mSorter.value.field) {
      column.sorter = true
      column.defaultSortOrder = mSorter.value.order || 'ascend'
    } else {
      column.defaultSortOrder = undefined
    }
    if (!column.customRender && column.component) {
      const viewCom = ViewMap[column.component as any] || ViewMap['Default']
      column.customRender = (e: any) => {
        return h(viewCom, {
          data: e,
          column
        })
      }
    }
  })
  if (props.actions && props.actions.length) {
    return [
      ...arr,
      {
        title: '操作',
        dataIndex: '__ACTION__',
        key: '__ACTION__',
        align: 'center',
        customRender(data: any): any {
          return h(TableAction, {
            actions: props.actions,
            dropdownActions: props.dropdownActions,
            data
          })
        }
      } as MTableColumnType
    ]
  } else {
    return arr
  }
}
// 数据源
const mDataSource = ref<any>([])

// 列定义
const mColumns = ref<Array<MTableColumnType>>(handleColumns(props.columns))
// 分页对象定义
const mPagination = ref<PaginationProps>({
  current: 1,
  pageSize: 10,
  total: 0,
  showQuickJumper: true,
  ...props.pagination
})
const tableRef = ref(null);
const isChange = ref<Number>(0);
const roleID = ref<Number>(0);
const isOk = ref<String>('');
const parentOrgID = ref<Number>(0)
const orgCode = {
  "OrgID": 0 //根组织
}
const reqeustParams = reactive({
  curPageNum: mPagination.value.current,
  numPerPage: mPagination.value.pageSize,

  parameter: {
    orgID: 1,
    onlyThis: true,
    roleID: 4

  }
})
const reqeustDeviceParams = reactive({
  curPageNum: mPagination.value.current,
  numPerPage: mPagination.value.pageSize,

  parameter: {
    orgID: null,
    onlyThis: true,
    edgeHardwareTypeId: 1,
    hostDeviceTypeId: 1
  }
})
const requestHostParam = reactive({
  method: "getList",
  hostDeviceTpye: {
    hostDeviceTpyeId: 1,
    name: "string",
    icon: "string",
    description: "string"
  }
})
const requestEdgeParam = reactive({
  method: "getList",
  edgeHardwareType: {
    edgeHardwareTypeId: 1,
    name: "string",
    icon: "string",
    description: "string"
  }
})
const testData = [{
  "id": "1",
  "parentId": "0",
  "name": "一级菜单1",
  "children": [{
    "id": "4",
    "parentId": "1",
    "name": "二级菜单11",
    "children": [{
      "id": "7",
      "parentId": "4",
      "name": "三级菜单111"
    }]
  }, {
    "id": "5",
    "parentId": "1",
    "name": "二级菜单12"
  }]
}, {
  "id": "2",
  "parentId": "0",
  "name": "一级菜单2",
  "children": [{
    "id": "6",
    "parentId": "2",
    "name": "二级菜单21"
  }]
}, {
  "id": "3",
  "parentId": "0",
  "name": "三级菜单3"
}]
watch(() => props.columns, () => {
  regisiter.updateColumns(props.columns)
}, {
  deep: true
})
watch(() => props.api, () => {
  regisiter.reload(requestEdgeParam)
}, {
  deep: true
})
// 监听分页对象
watch(() => props.pagination, () => {
  mPagination.value = {
    ...mPagination.value,
    ...props.pagination
  }
  requestData({})
}, {
  deep: true
})

const requestData = (params: any): Promise<any> => {
  let mArray: any = []
  let mId: any = []
  let apiFun: ((param: any) => Promise<any>) | undefined
  return new Promise((resolve, reject) => {
    if (props.api && typeof props.api == 'function') {
      apiFun = props.api
      console.log('function------+++', props.api);

    } else if (props.api && typeof props.api == 'string') {
      apiFun = (param: any) => request.post(props.api as any, param) as any
    }
    if (apiFun) {
      const sorter = mSorter.value
      // let reqeustParams = {
      //   pageNum: mPagination.value.current,
      //   pageSize: mPagination.value.pageSize,
      //   orderBy: (sorter.order && sorter.field) ? `${sorter.field} ${sorter.order.replace('end', '')}` : undefined,
      //   ...params,
      //   ...props.params
      // }

      // if (props.beforeFetch && typeof props.beforeFetch == 'function') {
      //   reqeustParams = props.beforeFetch(reqeustParams)
      // }
      // apiFun(reqeustParams).then((res: any)=>{
      console.log('props.beforeFetch', props.title);
      let param = {}
      if (props.title === '部门') {
        param = orgCode
      }
      if (props.title === '角色') {
        console.log('角色----');
      }
      if (props.title === '宿主') {
        console.log('宿主----');
        param = requestHostParam
      }
      if (props.title === '边缘') {
        console.log('边缘----');
        param = requestEdgeParam
      }
      if (props.title === '用户') {
        console.log('用户管理----');
        param = reqeustParams
      }
      if (props.title === '设备管理' || props.title === '注油点列表') {
        console.log('设备管理----');
        param = reqeustDeviceParams
      }
      apiFun(param).then((res: any) => {
        if (props.simple) {
          // mDataSource.value = toTreeData(res.content.rows || res.content) as any
          mDataSource.value = testData as any

        } else {
          if (props.title === '用户') {

            res.content.data.forEach((item: any, index: any) => {
              console.log('vvvvvvvv', item);
              item.role = item.role.name
              item.organizational = item.organizational.name
              mDataSource.value.push(item)

            })


            console.log('用户用户用户', mDataSource.value);
            // console.log('用户用户用户----', newObj);
            if (mDataSource.value.length !== res.content.totalNum) {

              reqeustParams.parameter.orgID = reqeustParams.parameter.orgID + 1
              // reqeustParams.parameter.roleID = reqeustParams.parameter.roleID + 1

              regisiter.reload(reqeustParams)

            }

          } else if (props.title === '宿主') {

            console.log('字典字典字典', res.content);

            let type = {}
            res.content.forEach((item: any, index: any) => {
              console.log('item---', item);
              Object.keys(item).forEach(key => {
                console.log('key:', key, 'value:', item[key]);
                if (key === 'hostDeviceTpyeId') {
                  type = { 'deviceTpye': '宿主设备' }
                  Object.assign(item, type)
                }
              })
              mDataSource.value.push(item)

            })

          } else if (props.title === '边缘') {

            console.log('边缘边缘边缘边缘', res.content);

            let type = {}
            res.content.forEach((item: any, index: any) => {
              console.log('item---', item);
              Object.keys(item).forEach(key => {
                console.log('key:', key, 'value:', item[key]);
                if (key === 'edgeHardwareTypeId') {
                  type = { 'deviceTpye': '边缘网关' }
                  Object.assign(item, type)
                }
              })
              mDataSource.value.push(item)

            })

          } else if (props.title === '设备管理') {

            console.log('设备管理设备管理', res.content);

            let name = ''
            // let tmpData = []
            // let type = {}
            res.content.data.forEach((item: any, index: any) => {
              console.log('item---', item);
              Object.keys(item).forEach(key => {
                console.log('key:', key, 'value:', item[key]);
                if (key === 'hardwareType' || key === 'deviceTpye') {
                  item[key] = item[key].name
                  // Object.assign(type,item[key])
                }
                if (key === 'currState') {
                  item[key] = item[key].string
                }
                if (key === 'registerTime') {

                  item[key] = dayjs(item[key]).format('YYYY-MM-DD HH:mm:ss');
                  // item[key] = item[key].string
                }
                if (key === 'organizational') {
                  item[key].forEach((item: any, index: any) => {
                    Object.keys(item).forEach(key => {
                      if (key === 'name') {
                        name = item[key]
                        return
                      }
                    })
                    console.log('name----', name);


                  })
                  item[key] = name
                }
              })
              mDataSource.value.push(item)

            })

          } else if (props.title === '注油点列表') {

            console.log('注油点列表+++++===', oilPipeName);


            res.content.data.forEach((item: any, index: any) => {

              Object.keys(item).forEach(key => {
                if (key === 'oilPipes') {
                  console.log('item---', item[key]);

                  item[key].forEach((item: any, index: any) => {
                    if (item.name === oilPipeName) {
                      console.log('干油管道injector', item.injector);
                      item.injector.forEach((item: any, index: any) => {
                        mDataSource.value.push(item)
                      })
                    }
                    // console.log('干油管道injector',item);
                    // Object.keys(item).forEach(key => {

                    //   if (key === 'injector') {
                    //     if(item[key].length !== 0){
                    //       console.log('injector',item[key]);
                    //       item[key].forEach((item: any, index: any) => {
                    //         mDataSource.value.push(item)
                    //       })
                    //     }


                    //   }
                    // })
                  })
                }
              })


              // mDataSource.value.push(item)

            })

          }

          else {


            mPagination.value.total = res.content.recordCount || res.content.length
            mDataSource.value = res.content.rows || res.content
            mArray = res.content.rows || res.content
            // mDataSource.value = testData as any

            let children = { "children": [] }
            res.content.forEach((item: any, index: any) => {

              if (props.title === '角色') {

                if (item.permissions === 'administrator') {
                  mDataSource.value[index].permissions = '超级管理员'
                  console.log('----', item.permissions);
                }
                if (item.permissions === 'admin') {
                  mDataSource.value[index].permissions = '管理员'
                  console.log('----', item.permissions);
                }
                if (item.permissions === 'guest') {
                  mDataSource.value[index].permissions = '访客用户'
                  console.log('----', item.permissions);
                }
                console.log('33333', item.id);
                console.log('vvvvvvvv', mDataSource.value);
                if (res.content.length - 1 === index) {
                  // console.log('----', item.id);
                  // console.log('index----', res.content.length);
                  roleID.value = item.id + 1
                  // console.log('item.id', roleID.value);
                  handleSend(roleID.value)
                }
              }
              if (props.title === '部门') {
                if (res.content.length - 1 === index) {
                  // console.log('----', item.id);
                  // console.log('index----', res.content.length);
                  parentOrgID.value = item.id
                  // console.log('item.id', parentOrgID.value);
                  handleSend(parentOrgID.value)
                }
                mId.push(item.id)
                if (Object.keys(param).length !== 0) {
                  Object.assign(mDataSource.value[index], children)
                }
              }
            });
            if (isChange.value === 0) {
              orgCode.OrgID = 1
            } else if (isChange.value === 1) {
              isChange.value = 0
              orgCode.OrgID = mId[0]
            }
          }
        }

        resolve(res)
      }).catch(reject)
    } else {
      resolve({})
    }
  })
}
const duplicateRequest = (params: any): Promise<any> => {
  let apiFun: ((params: any) => Promise<any>) | undefined
  return new Promise((resolve, reject) => {
    if (props.api && typeof props.api == 'function') {
      apiFun = props.api
    } else if (props.api && typeof props.api == 'string') {
      apiFun = (params: any) => request.post(props.api as any, params) as any
    }
    if (apiFun) {
      // apiFun(reqeustParams).then((res: any)=>{
      apiFun(params).then((res: any) => {
        if (props.simple) {
          // mDataSource.value = toTreeData(res.content.rows || res.content) as any
          mDataSource.value = testData as any

        } else {
          // mPagination.value.total = res.content.recordCount || res.content.length

          // let children = {"children":res.content}
          // let children = res.content[0]
          // ((mDataSource.value[0])as any).children.push(res.content[0]) 
          // Object.assign(mDataSource.value[0],children[0])
          // console.log('children----', res.content[0]);
          // console.log('children',mDataSource.value);
        }
        resolve(res)
      }).catch(reject)
    } else {
      resolve({})
    }
  })
}
const onexpand = async (expanded: boolean, record: any) => {//绑定的点击行事件
  console.log(expanded, record)//expanded =true ||false,record：本行数据
  if (expanded == true) {
    isChange.value = 1;
    console.log(record.orgId);
    orgCode.OrgID = record.orgId
    console.log('orgCode======', orgCode);
    console.log('record', record);
    const children: any = await duplicateRequest(orgCode) as any
    console.log('======', children.content);
    console.log('+++++++', children);
    record.children = [];
    let subItem = { "children": [] }
    if (children.content.length !== 0) {
      children.content.forEach((item: any, index: any) => {
        console.log('33333', item);
        Object.assign(item, subItem)
        record.children?.push(item);

      });
    }
  } else {

  }
}
/**
 * 表格事件处理
 * @param pagination 
 * @param filters 
 * @param sorter 
 */
const handleTableChange = (pagination: PaginationProps, filters: any, sorter: any) => {
  mPagination.value = {
    ...mPagination.value,
    ...pagination
  }
  mSorter.value = {
    ...mSorter.value,
    ...sorter
  }
  emits('change', mPagination.value, filters, mSorter.value)
  requestData({})
}
const regisiter = {
  reload(opt) {
    return requestData(opt)
  },
  setTableSize(size) {
    sizeRef.value = size
    tableToolbarRef.value?.setMiDuSelectdKeys([size])
  },
  updateColumns(columns) {
    mColumns.value = handleColumns(columns)
  },
} as TableActionType
onMounted(() => {
  if (props.immediate) {
    // if (props.title === '用户管理') {
    //     console.log('用户管理')

    //     }
    requestData({})
  }
})
defineExpose({
  ...regisiter
})
</script>

<style lang="less" scoped></style>